package com.ws.configuration;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ws.common.authentication.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginHandler implements HandlerInterceptor {
    /**
     * 在拦截器监听的接口之前执行的函数
     * @param request 浏览器发送给服务器的数据
     * @param response 服务器响应的数据
     * @param handler 拦截对象
     * @return 波尔类型 true放行 false拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头部的token
        String token = request.getHeader("jwt");

        JSONObject data = new JSONObject();
        try {
            JWTUtil.verify(token);
            return true;
        }catch (TokenExpiredException e1) {
            data.put("mes","token过期");
        } catch (AlgorithmMismatchException e2) {
            data.put("mes","token算法不一致");
        } catch (SignatureVerificationException e3) {
            data.put("mes","token认证失败");
        } catch (Exception e4) {
            data.put("mes","token无效");
        }
        data.put("code",401);
        response.addHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(data.toJSONString());
        return false;


//        //判断session会话中是否存在userInfo这个数据 若存在放行 反之拦截并返回错误信息
//        HttpSession session = request.getSession();
//        JSONObject data = new JSONObject();
//        //未登录
//        if(session.getAttribute("userInfo") == null) {
//            data.put("code",401);
//            data.put("msg","用户未登录，请重新登录");
//
//            response.addHeader("Content-Type","application/json;charset=utf-8");
//            PrintWriter out = response.getWriter();
//            out.print(data.toJSONString());
//            return false;
//        } else {
//            return true;
//        }
//
    }
}
